import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:gzmall_app/common/refresh_listview.dart';
import 'package:gzmall_app/goods/goods_details_page.dart';
import 'package:gzmall_app/model/favorites.dart';
import 'package:gzmall_app/model/product.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/api.dart';

class CollectPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => CollectPageState();
}

class CollectPageState extends State<CollectPage> {
  List<Favorites> _products = [];

  int _curPage = 1;
  RefreshListView _refreshListView;
  bool _showEmpty = false;

  @override
  void initState() {
    super.initState();
    _getFavoritesProduct("Spu", 1);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _createAppBar(),
      body: _buildGoodList(context),
    );
  }

  _createAppBar() {
    return new AppBar(
      elevation: 0.0,
      title: new Text("我的收藏"),
      leading: new IconButton(
        icon: new Icon(Icons.arrow_back_ios),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
      actions: <Widget>[],
    );
  }

  Widget _buildGoodList(BuildContext context) {
    _refreshListView = RefreshListView(
      enablePullUp: true,
      enablePullDown: true,
      onRefresh: _onRefresh,
      child: _buildList(),
      showEmpty: _showEmpty,
      onReload: () {
        _getFavoritesProduct("Spu", 1);
      },
      emptyView: Container(
          width: double.infinity,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Image.asset(
                "images/no_collection.png",
                width: 100.0,
                height: 100.0,
              ),
              Padding(
                padding: const EdgeInsets.only(top: 10.0),
                child: Text(
                  '暂无收藏记录',
                  style: TextStyle(fontSize: 18.0, color: ColorCommon.black1),
                ),
              ),
            ],
          )),
    );
    return _refreshListView;
  }

  Widget _buildList() {
    List<Widget> _productViewList = _products
        .map((item) => new InkWell(
              child: Container(
                color: Colors.white,
                margin: const EdgeInsets.only(bottom: 1.0),
                padding: const EdgeInsets.only(
                    left: 10.0, right: 10.0, top: 10.0, bottom: 10.0),
                child: Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      item?.spu?.avatar != null
                          ? CachedNetworkImage(
                              imageUrl: item?.spu?.avatar,
                              fit: BoxFit.fill,
                              width: 120.0,
                              height: 120.0,
                            )
                          : Container(
                              color: Colors.grey,
                              width: 120.0,
                              height: 120.0,
                            ),
                      Expanded(
                        child: Container(
                          height: 120.0,
                          margin: const EdgeInsets.only(left: 10.0),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              Expanded(
                                child: Text(
                                  item?.spu?.name ?? "",
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(
                                      fontSize: 14.0,
                                      color: ColorCommon.black1),
                                ),
                              ),
                              Container(
                                padding: const EdgeInsets.only(top: 4.0),
                                child: Row(children: <Widget>[
                                  item?.spu?.directSale != null &&
                                          item.spu.directSale
                                      ? Padding(
                                          padding:
                                              const EdgeInsets.only(right: 4.0),
                                          child: _getTagView(
                                              "自营",
                                              Colors.white,
                                              ColorCommon.primaryColor,
                                              ColorCommon.primaryColor))
                                      : Container(),
                                  item?.spu?.promotion != null &&
                                          item.spu.promotion
                                      ? Padding(
                                          padding:
                                              const EdgeInsets.only(right: 4.0),
                                          child: _getTagView(
                                              "促销价",
                                              Colors.white,
                                              ColorCommon.primaryColor,
                                              ColorCommon.primaryColor),
                                        )
                                      : Container(),
                                  Expanded(
                                    child: Text(
                                      "98.0%好评",
                                      style: TextStyle(
                                          fontSize: 14.0,
                                          color: ColorCommon.grey8),
                                    ),
                                  ),
                                ]),
                              ),
                              Container(
                                padding: const EdgeInsets.only(top: 4.0),
                                child: Row(
                                    crossAxisAlignment: CrossAxisAlignment.end,
                                    children: <Widget>[
                                      Text(
                                        "¥" +
                                            (item?.spu?.promotion != null &&
                                                    item.spu.promotion
                                                ? (item?.spu
                                                        ?.lowPromotionPrice ??
                                                    "0.0")
                                                : (item?.spu?.lowSalePrice ??
                                                    "0.0")),
                                        style: TextStyle(
                                            fontSize: 18.0,
                                            color: ColorCommon.primaryColor),
                                      ),
                                      item?.spu?.promotion != null &&
                                              item.spu.promotion
                                          ? Expanded(
                                              child: Padding(
                                                padding: const EdgeInsets.only(
                                                    left: 4.0),
                                                child: Text(
                                                  "¥" +
                                                      (item?.spu
                                                              ?.lowSalePrice ??
                                                          "0.0"),
                                                  style: TextStyle(
                                                    fontSize: 14.0,
                                                    color: ColorCommon.grey8,
                                                    decoration: TextDecoration
                                                        .lineThrough,
                                                    decorationStyle:
                                                        TextDecorationStyle
                                                            .solid,
                                                  ),
                                                ),
                                              ),
                                            )
                                          : Container(),
                                    ]),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ]),
              ),
              onTap: () {
                if (item?.spu?.id != null) {
                  Navigator.of(context)
                      .push(new MaterialPageRoute(builder: (_) {
                    return new GoodsDetailsPage(productId: item?.spu?.id);
                  }));
                }
              },
            ))
        .toList();
    return ListView(
      padding: EdgeInsets.only(top: 0.0),
      children: _productViewList,
    );
  }

  Widget _getTagView(
      String text, Color bgColor, Color borderColor, Color textColor,
      {DecorationImage image}) {
    BoxDecoration decoration;
    if (image == null) {
      decoration = BoxDecoration(
          color: bgColor,
          border: Border.all(color: borderColor),
          borderRadius: BorderRadius.all(Radius.circular(100.0)));
    } else {
      decoration = BoxDecoration(image: image);
    }
    return Container(
      padding: const EdgeInsets.only(left: 4.0, right: 4.0),
      decoration: decoration,
      child: Text(
        text,
        style: TextStyle(fontSize: 13.0, color: textColor),
      ),
    );
  }

  void _onRefresh(bool up) {
    if (up) {
      _getFavoritesProduct("Spu", 1);
    } else {
      _getFavoritesProduct("Spu", _curPage + 1);
    }
  }

  _getFavoritesProduct(String type, int page) async {
    bool isGetNew = page == 1;
    Map<String, String> params = {"type": type, "page": page.toString()};
    NetUtil.get(
        context,
        Api.favorites,
        (data, message) {
          if (!mounted) return;
          _curPage = page;
          var _dataList = (data as List)
              ?.map((e) => e == null ? null : Favorites.fromJson(e))
              ?.toList();
          setState(() {
            _showEmpty =
                isGetNew && (_dataList == null || _dataList.length <= 0);
            if (isGetNew) {
              _products = _dataList;
            } else {
              _products.addAll(_dataList);
            }
          });
          if (_refreshListView != null) {
            _refreshListView.refreshCompleted(isGetNew,
                hasMore: _dataList != null && _dataList.length >= Api.pageSize);
          }
        },
        params: params,
        errorCallBack: (e) {
          setState(() {
            _showEmpty =
                isGetNew && (_products == null || _products.length <= 0);
          });
          if (_refreshListView != null) {
            _refreshListView.refreshCompleted(isGetNew);
          }
        });
  }
}
